package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;


import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.OrderVo;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.vo.SkuLockVo;
import com.spzx.product.vo.SkuPriceVo;
import com.spzx.system.api.RemoteUserService;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.temporal.ValueRange;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-26
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private RemoteSkuStockService remoteSkuStockService;


    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private RabbitService rabbitService;


    /**
     * 订单结算：交易数据汇总
     *
     * @return
     */
    @Override
    public TradeVo orderTradeData() {
        TradeVo tradeVo = new TradeVo();
        //1.封装 用户购物车中选中商品列表
        //1.1 远程调用购物车服务获取选中商品列表
        R<List<CartInfo>> r = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("购物车接口有误请稍后再试");
        }
        //1.2 封装到tradeVo中
        List<CartInfo> cartInfoList = r.getData();
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("购物车为空，请先添加商品");
        }
        //1.3 将购物车商品转为订单明细
        List<OrderItem> orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).collect(Collectors.toList());
        tradeVo.setOrderItemList(orderItemList);

        //2.计算订单中商品总金额
        BigDecimal totalAmount = orderItemList
                .stream()
                .map(orderItem -> {
                    return orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()));
                }).reduce(BigDecimal.ZERO, BigDecimal::add);//reduce计算map的结果
        tradeVo.setTotalAmount(totalAmount);

        //3.生成本次订单交易流水号；避免订单重复提交或订单提交超时
        String tradeNo = generateTradeNo(SecurityUtils.getUserId());
        tradeVo.setTradeNo(tradeNo);
        return tradeVo;
    }


    /**
     * 基于用户ID生成订单流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        String tradeKey = "user:tradeNo:" + userId;
        String tradeNo = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(tradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }


    /**
     * 保存订单
     *
     * @param orderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitOrder(OrderVo orderVo) {
        //1.验证流水号，避免回退造成订单重复提交或用户长时间停留在订单确认页
        String tradeNo = orderVo.getTradeNo();
        //1.1 利用lua脚本保证判断跟删除流水号原子性
        String tradeKey = "user:tradeNo:" + SecurityUtils.getUserId();
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(tradeKey), tradeNo);
        if (flag.intValue() == 0) {
            throw new ServiceException("订单已提交或订单超时");
        }

        //2.验证商品价格是否变更,如果订单明细中任意商品价格变更，业务终止
        //2.1 获取订单明细列表，获取订单中商品SKUID列表
        List<OrderItem> orderItemList = orderVo.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("订单明细为空");
        }
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
        //2.2 远程调用商品服务批量获取商品最新价格，封装Map<商品ID，最新价格>方便获取某件商品价格
        R<List<SkuPriceVo>> r = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("商品服务批量获取商品最新价格接口有误请稍后再试");
        }
        List<SkuPriceVo> skuPriceVoList = r.getData();
        Map<Long, BigDecimal> skuNewPriceMap = skuPriceVoList.stream()
                .collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        //2.3 创建价格错误提示信息变量
        String priceErrorMsg = "";
        //2.4 如果价格存在变更，更新购物车中商品价格
        for (OrderItem orderItem : orderItemList) {
            //TODO BigDecimal类型比较一定要用compareTo方法，不能用equals
            if (orderItem.getSkuPrice().compareTo(skuNewPriceMap.get(orderItem.getSkuId())) != 0) {
                priceErrorMsg += orderItem.getSkuName() + "\t";
            }
        }
        //判断是否有价格变更
        if (!ObjectUtils.isEmpty(priceErrorMsg)) {
            //2.4.1 通过购物车途径保存订单，远程调用购物车服务更新购物车商品价格
            if (!orderVo.getIsBuy()) {
                R<Boolean> r1 = remoteCartService.updateCartPrice(SecurityUtils.getUserId(), SecurityConstants.INNER);
                if (R.FAIL == r1.getCode()) {
                    throw new ServiceException("购物车服务更新购物车商品价格接口有误请稍后再试");
                }
            }
            //2.4.1 将错误提示信息返回给客户端
            throw new ServiceException("订单商品" + priceErrorMsg + "价格有变更，请重新下单");
        }
        //3.保存订单及订单明细列表包括订单日志
        OrderInfo orderInfo = this.saveOrder(orderVo);

        //4.锁定商品库存
        //4.1 获取要锁定商品VO列表
        List<SkuLockVo> skuLockVoList = orderVo.getOrderItemList().stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            BeanUtils.copyProperties(orderItem, skuLockVo);
            return skuLockVo;
        }).collect(Collectors.toList());
        //4.2 远程调用商品服务库存锁定
        R<String> r2 = remoteSkuStockService.checkAndLock(orderInfo.getOrderNo(), skuLockVoList, SecurityConstants.INNER);
        //4.3 判断远程调用锁定结果
        if (R.FAIL == r2.getCode()) {
            throw new ServiceException(r2.getMsg());
        }

        //5.通过购物车途径保存订单,清理购物车中选中商品
        if (!orderVo.getIsBuy()) {
            R<Boolean> r1 = remoteCartService.deleteCartCheckedList(SecurityUtils.getUserId(), SecurityConstants.INNER);
            if (R.FAIL == r1.getCode()) {
                throw new ServiceException(r1.getMsg());
            }
        }

        //TODO 发送延迟延迟消息 基于死信实现延迟消息-作业
        //6.返回订单ID，跟支付页展示订单信息对接
        return orderInfo.getId();
    }


    /**
     * 保存订单、订单明细列表包括订单日志
     *
     * @param orderVo
     * @return
     */
    @Override
    public OrderInfo saveOrder(OrderVo orderVo) {
        //1.保存订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(SecurityUtils.getUserId());
        orderInfo.setNickName(SecurityUtils.getUsername());
        //1.1 生成全局唯一订单编号, 日期+全局唯一ID 采用MP封装的Twitter开源雪花算法，趋势递增
        String today = DateUtils.getDate().replaceAll("-", "");
        String orderNo = today + IdWorker.getIdStr();
        orderInfo.setOrderNo(orderNo);

        BigDecimal totalAmount = orderVo.getOrderItemList()
                .stream()
                .map(orderItem -> {
                    return orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()));
                }).reduce(BigDecimal.ZERO, BigDecimal::add);//reduce计算map的结果
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal("0"));
        orderInfo.setOriginalTotalAmount(totalAmount);
        BigDecimal feightFee = new BigDecimal("0");
        if (totalAmount.compareTo(new BigDecimal("99")) == 1) {
            feightFee = new BigDecimal("6");
        }
        orderInfo.setFeightFee(feightFee);
        orderInfo.setOrderStatus(0);
        orderInfo.setRemark(orderVo.getRemark());
        //1.1 远程调用用户服务获取地址薄信息
        R<UserAddress> r = remoteUserAddressService.getUserAddress(orderVo.getUserAddressId(), SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("远程调用用户服务获取地址薄信息接口有误请稍后再试");
        }
        UserAddress userAddress = r.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        orderInfo.setCreateBy(SecurityUtils.getUsername());
        baseMapper.insert(orderInfo);
        Long orderId = orderInfo.getId();

        //2.保存订单明细
        for (OrderItem orderItem : orderVo.getOrderItemList()) {
            orderItem.setOrderId(orderId);
            orderItem.setCreateBy(SecurityUtils.getUsername());
            orderItemMapper.insert(orderItem);
        }

        //3.记录订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setOperateUser(SecurityUtils.getUsername());
        orderLog.setProcessStatus(0);
        orderLog.setNote(orderVo.getRemark());
        orderLog.setCreateBy(SecurityUtils.getUsername());
        orderLogMapper.insert(orderLog);
        return orderInfo;
    }

    /**
     * 商品详情页选择立即购买，将商品作为订单明细
     *
     * @param skuId
     * @return
     */
    @Override
    public TradeVo buy(Long skuId) {
        TradeVo tradeVo = new TradeVo();
        //1.远程调用商品服务获取商品信息
        R<ProductSkuVo> r = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("远程调用商品服务获取商品信息接口有误请稍后再试");
        }
        ProductSkuVo skuVo = r.getData();
        tradeVo.setTotalAmount(skuVo.getSalePrice());
        //构建商品明细
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(skuVo.getSkuName());
        orderItem.setThumbImg(skuVo.getThumbImg());
        orderItem.setSkuPrice(skuVo.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);
        tradeVo.setOrderItemList(orderItemList);

        //生成本次订单流水号
        String tradeNo = generateTradeNo(SecurityUtils.getUserId());
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setIsBuy(true);

        return tradeVo;
    }

    /**
     * 查询订单 包含订单明细
     *
     * @param orderStatus
     * @return
     */
    @Override
    public List<OrderInfo> findOrderList(Integer orderStatus) {
        //1.根据用户ID或者状态查询订单列表
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getUserId, SecurityUtils.getUserId());
        queryWrapper.eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus);
        queryWrapper.orderByDesc(OrderInfo::getCreateTime);
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(orderInfoList)) {
            //2.获取到订单明细列表 一次性将所有订单包含所有订单明细，减少查询MySQL次数
            //2.1 获取订单ID列表
            List<Long> orderIdList = orderInfoList.stream().map(OrderInfo::getId).collect(Collectors.toList());
            //2.2 获取到订单下包含所有明细
            LambdaQueryWrapper<OrderItem> itemLambdaQueryWrapper = new LambdaQueryWrapper<>();
            itemLambdaQueryWrapper.in(OrderItem::getOrderId, orderIdList);
            List<OrderItem> allOderItemList = orderItemMapper.selectList(itemLambdaQueryWrapper);
            //2.3 将所有订单明细列表 按照订单ID进行分组 得到Map key:订单ID value:订单明细列表
            Map<Long, List<OrderItem>> orderItemMap = allOderItemList
                    .stream()
                    //根据订单明细中订单ID进行分组
                    .collect(Collectors.groupingBy(OrderItem::getOrderId));

            //2.3 封装到订单对象中
            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(orderItemMap.get(orderInfo.getId()));
            }
        }
        return orderInfoList;
    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {
        //1.查询订单状态 未付款订单可以取消
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if (orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户主动取消");
            baseMapper.updateById(orderInfo);

            //2.记录订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderId);
            orderLog.setOperateUser(SecurityUtils.getUsername());
            orderLog.setProcessStatus(-1);
            orderLog.setNote(orderInfo.getCancelReason());
            orderLog.setCreateBy(SecurityUtils.getUsername());
            orderLogMapper.insert(orderLog);

            //2.TODO 基于可靠性MQ消息-解锁商品库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        //1.根据订单编号查询订单信息
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        //2.根据订单ID查询订单明细
        if (orderInfo != null) {
            LambdaQueryWrapper<OrderItem> itemLambdaQueryWrapper = new LambdaQueryWrapper<>();
            itemLambdaQueryWrapper.eq(OrderItem::getOrderId, orderInfo.getId());
            List<OrderItem> orderItemList = orderItemMapper.selectList(itemLambdaQueryWrapper);
            orderInfo.setOrderItemList(orderItemList);
        }
        return orderInfo;
    }

    /**
     * 支付成功后，需要更新订单状态：已支付
     * @param orderNo
     */
    @Override
    public void paySuccessHandler(String orderNo) {
        OrderInfo orderInfo = this.getByOrderNo(orderNo);
        if (orderInfo != null) {
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            baseMapper.updateById(orderInfo);
        }
    }


}
